<script setup>
import { ref, onMounted } from 'vue';
import { ElTable, ElPagination, ElMessageBox, ElMessage } from 'element-plus';
import { searchUsers, deleteUser } from '@/api/user';

const loading = ref(false);
const users = ref([]);
const total = ref(0);
const queryParams = ref({
  page: 1,
  pageSize: 10,
  username: '',
  email: '',
  phone: ''
});

const fetchUsers = async () => {
  loading.value = true;
  try {
    const response = await searchUsers(queryParams.value);
    users.value = response.data.list;
    total.value = response.data.total;
  } catch (error) {
    console.error('获取用户列表失败:', error);
  } finally {
    loading.value = false;
  }
};

onMounted(fetchUsers);

const handleDelete = (id) => {
  ElMessageBox.confirm('确定要删除该用户吗？', '提示', {
    type: 'warning'
  }).then(async () => {
    await deleteUser(id);
    ElMessage.success('删除成功');
    fetchUsers();
  });
};

const handlePageChange = (page) => {
  queryParams.value.page = page;
  fetchUsers();
};
</script>

<template>
  <div class="user-list-container">
    <el-card>
      <template #header>
        <div class="card-header">
          <h3>用户管理</h3>
        </div>
      </template>
      <el-form :inline="true" @submit.native.prevent>
        <el-form-item label="用户名">
          <el-input v-model="queryParams.username" placeholder="请输入用户名" clearable />
        </el-form-item>
        <el-form-item label="邮箱">
          <el-input v-model="queryParams.email" placeholder="请输入邮箱" clearable />
        </el-form-item>
        <el-form-item label="手机号">
          <el-input v-model="queryParams.phone" placeholder="请输入手机号" clearable />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="fetchUsers">查询</el-button>
        </el-form-item>
      </el-form>

      <el-table :data="users" v-loading="loading">
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="username" label="用户名" />
        <el-table-column prop="email" label="邮箱" />
        <el-table-column prop="phone" label="手机号" />
        <el-table-column label="操作" width="180">
          <template #default="scope">
            <el-button type="danger" size="small" @click="handleDelete(scope.row.id)">
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <el-pagination
          background
          layout="prev, pager, next"
          :total="total"
          :page-size="queryParams.pageSize"
          @current-change="handlePageChange"
      />
    </el-card>
  </div>
</template>

<style lang="scss" scoped>
.user-list-container {
  padding: 20px;
}
</style>